package com.h3bpm.web.utils;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

public class PdfWaterMark {

//    public static void main(String[] args) throws Exception {
//
//        String inPath = "d:/test/test1.pdf";
//        String sfPath = Thread.currentThread().getContextClassLoader().getResource("")+"lib/sjyz.png";
//        String imgPath = "d:/test/2wm.jpg";
//        String out = "d:/test/test9999.pdf";
//
//        PdfWater zc = PdfWaterMark.blueTextWater("中车戚墅堰机车有限公司", 100, 200, 55, 0.5f, 45);
//        //2wm
//        PdfWater tp = PdfWaterMark.getImageWater(imgPath ,-20f,-20f,50,0.5f);
//        PdfWater sf = PdfWaterMark.getImageWater(sfPath ,-100f,25f,100,0.5f);
//
//        List<PdfWater> pdfWaterList =  new ArrayList<>();
//
//        pdfWaterList.add(zc);
//        pdfWaterList.add(sf);
//        pdfWaterList.add(tp);
//
//
//        FileInputStream inputStream = new FileInputStream(inPath);
//
//        byte[] bytes = new byte[inputStream.available()];
//        inputStream.read(bytes);
//
//        byte[] byteArr = PdfWaterMark.addWaterMark(bytes, pdfWaterList);
//
//        FileOutputStream bos = new FileOutputStream(out);
//
//        BufferingOutputStream bfos = new BufferingOutputStream(bos);
//
//        bfos.write(byteArr);
//
//        close(bfos);
//        close(bos);
//        close(inputStream);
//
//    }


    private static BaseFont basefont;
    private  static BaseFont getFont(){


        if (basefont == null) {
            try {
                String property = System.getProperties().getProperty("os.name");

                if ("Linux".equalsIgnoreCase(property)) {
                    basefont = BaseFont.createFont("/usr/share/fonts/chinese/TureType/simfang.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                }else{
                    basefont = BaseFont.createFont("C:/WINDOWS/Fonts/SIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                }

            } catch ( Exception e) {
                e.printStackTrace();
                System.out.println(".........pdfWaterMark ..获取字体失败");
            }

        }

        return basefont;
    }

    /**
     *  传入二进制,返回二进制
     * @param bytes
     * @param list
     * @return
     * @throws Exception
     */
    public static  byte[] addWaterMark(byte[] bytes , List<PdfWater> list) throws Exception {

        byte[] byteArray = null;

        if (bytes == null || bytes.length == 0) {
            return null;
        }
        if (list == null || list.size() == 0) {
            return null;
        }

        // 待加水印的文件
        PdfReader reader = new PdfReader(bytes);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        // 加完水印的文件
        PdfStamper stamper = new PdfStamper(reader, bos);

        int total = reader.getNumberOfPages() + 1;
        PdfContentByte content;
        Rectangle rectangle ;

        // 循环对每页插入水印
        for (int i = 1; i < total; i++) {
            content = stamper.getOverContent(i);
            rectangle = reader.getPageSize(i);

            // 开始
            content.beginText();

            for (int j = 0; j < list.size(); j++) {
                list.get(j).addWater(content, rectangle.getWidth(), rectangle.getHeight());
            }

            content.endText();
        }
        close(stamper);

        byteArray =  bos.toByteArray();

        close(bos);

        close(reader);

        return byteArray;
    }


    private static void close(Object object) {
        if (object == null) {
            return;
        }

        try {
            if (object instanceof OutputStream) {
                ((OutputStream) object).close();
            } else if (object instanceof InputStream) {
                ((InputStream) object).close();
            } else if (object instanceof PdfReader) {
                ((PdfReader) object).close();
            }else  if (object instanceof PdfStamper){
                ((PdfStamper) object).close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     *  创建图片水印
     * @param imagePath
     * @param left  位置 left ,right 都为正值, 以纸张左下角为原点,都为 负值以 右上角为原点
     * @param right
     * @param scaleAbsolute
     * @param fillOpacity
     * @return
     * @throws Exception
     */
    public static PdfWater getImageWater(String imagePath,float left,float right,float scaleAbsolute, float fillOpacity ) throws Exception {
        return new PdfWaterMark().new ImageWater(imagePath, left, right, scaleAbsolute, fillOpacity);

    }
    public static PdfWater getImageWater(byte [] imageByte,float left,float right,float scaleAbsolute, float fillOpacity ) throws Exception {
        return new PdfWaterMark().new ImageWater(imageByte, left, right, scaleAbsolute, fillOpacity);

    }

    /**
     *  创建文字水印
     * @param text
     * @param left 位置 left ,right 都为正值, 以纸张左下角为原点,都为 负值以 右上角为原点
     * @param right
     * @param fontSize
     * @param fillOpacity
     * @param rotation
     * @return
     * @throws Exception
     */
    public static PdfWater  redTextWater(String text, float left, float right, float fontSize, float fillOpacity, float rotation) throws  Exception{

        return new PdfWaterMark().new TextWater(text, left, right, fontSize, fillOpacity, rotation, BaseColor.RED);
    }
    public static PdfWater  blackTextWater(String text, float left, float right, float fontSize, float fillOpacity, float rotation) throws  Exception{
        return new PdfWaterMark().new TextWater(text, left, right, fontSize, fillOpacity, rotation, BaseColor.BLACK);
    }
    public static PdfWater  blueTextWater(String text, float left, float right, float fontSize, float fillOpacity, float rotation) throws  Exception{
        return new PdfWaterMark().new TextWater(text, left, right, fontSize, fillOpacity, rotation, BaseColor.BLUE);
    }
    public static PdfWater  grayTextWater(String text, float left, float right, float fontSize, float fillOpacity, float rotation) throws  Exception{
        return new PdfWaterMark().new TextWater(text, left, right, fontSize, fillOpacity, rotation, BaseColor.GRAY);
    }


    /**
     *  接口pdf 添加水印
     */
    public interface PdfWater{
        public void addWater(PdfContentByte content, float width, float height) throws  Exception;
    }

    /**
     *  添加图水印
     */
    private  class ImageWater implements PdfWater {



        float scaleAbsolute;
        Image image;
        PdfGState gs;
        float fillOpacity ;
        /**
         * 位置
         *  left ,right 都为正值, 以纸张左下角为原点,
         *  都为 负值以 右上角为原点
         *
         */
        float left;
        float right;

        /**
         *  创建图片水印
         * @param imagePath
         * @param left
         * @param right
         * @param scaleAbsolute
         * @param fillOpacity
         */
        public ImageWater(String imagePath,float left,float right,float scaleAbsolute, float fillOpacity ) throws  Exception {

            setData(left,right,scaleAbsolute,fillOpacity);

            createImage(imagePath);
        }

        /**
         * 创建图片水印
         * @param imageByte
         * @param left
         * @param right
         * @param scaleAbsolute
         * @param fillOpacity
         */
        public ImageWater(byte[] imageByte,float left,float right,float scaleAbsolute, float fillOpacity ) throws  Exception {

            setData(left,right,scaleAbsolute,fillOpacity);

            createImage(imageByte);
        }


        private void setData(float left,float right,float scaleAbsolute, float fillOpacity ){
            this.left = left;
            this.right = right;
            this.scaleAbsolute = scaleAbsolute;
            this.fillOpacity = fillOpacity;
            gs = new PdfGState();
            gs.setFillOpacity(fillOpacity);
        }


        @Override
        public void addWater(PdfContentByte content,float width,float height) throws Exception {
            content.setGState(gs);

            float left =  this.left<0? width-image.getScaledWidth()+this.left : this.left;
            float right =  this.right <0? height -image.getScaledHeight() + this.right : this.right;

            image.setAbsolutePosition(left, right);

            content.addImage(image);

        }

        /**
         *  获取图片
         * @throws Exception
         */
        private  void createImage(String imagePath) throws  Exception {
            if (image == null) {
                image = Image.getInstance(imagePath);
                image.scaleAbsolute( image.getScaledWidth()/(image.getScaledWidth()/this.scaleAbsolute),
                        image.getScaledHeight()/(image.getScaledWidth()/this.scaleAbsolute) );//重新设置宽高
            }

        }
        /**
         *  获取图片
         * @throws Exception
         */
        private  void createImage(byte [] imageByte) throws  Exception {
            if (image == null) {
                image = Image.getInstance(imageByte);
                image.scaleAbsolute( image.getScaledWidth()/(image.getScaledWidth()/this.scaleAbsolute),
                        image.getScaledHeight()/(image.getScaledWidth()/this.scaleAbsolute) );//重新设置宽高
            }

        }

    }

    private  class TextWater  implements PdfWater {


        float fillOpacity ;

        String text;

        /**
         * 位置
         *  left ,right 都为正值, 以纸张左下角为原点,
         *  都为 负值以 右上角为原点
         *
         */
        float left;
        float right;

        float fontSize;
        float rotation;

        BaseColor color;
        PdfGState gs;
        BaseFont base;

        /**
         *  创建文字水印
         * @param text
         * @param left
         * @param right
         * @param fontSize
         * @param fillOpacity
         * @param rotation
         * @param color
         * @throws Exception
         */
        public TextWater(String text, float left, float right, float fontSize, float fillOpacity, float rotation,BaseColor color) throws  Exception {
            this.text = text;
            this.left = left;
            this.right = right;
            this.fontSize = fontSize;
            this.fillOpacity = fillOpacity;
            this.rotation = rotation;

            this.color = color;

            gs = new PdfGState();
            gs.setFillOpacity(fillOpacity);
//            base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
            base = PdfWaterMark.getFont();

        }


        @Override
        public void addWater(PdfContentByte content,float width,float height){
            float left =  this.left<0? width+this.left : this.left;
            float right =  this.right <0? height + this.right : this.right;

            content.setGState(gs);
            content.setFontAndSize(base, fontSize);

            // 设置颜色 默认为黑色
            content.setColorFill(color);
            content.showTextAligned(Element.ALIGN_MIDDLE, text, left, right,rotation);


        }





    }

}
